package com.cgl.until;

import org.slf4j.Logger;

public class TextDocmentReadAndWriting {
    /**
     * 写入文件
     * @param fileName 文件路径
     * @param content  文件内容
     * @return 写入是否成功
     */
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(TextDocmentReadAndWriting.class);

    public boolean write(String fileName, String content) {
        try {
            java.io.FileWriter fw = new java.io.FileWriter(PropertiesRead.read("saveArticlePath")+fileName);
            logger.info("写入文件路径："+PropertiesRead.read("saveArticlePath")+fileName);
            fw.write(content);
            fw.close();
            return true;
        } catch (Exception e) {
            logger.error("写入文件失败："+e.getMessage());
            return false;
        }
    }
    public boolean update(String fileName, String content) {
        try {
            java.io.FileWriter fw = new java.io.FileWriter(PropertiesRead.read("saveArticlePath")+fileName);
            logger.info("更新文件路径："+PropertiesRead.read("saveArticlePath")+fileName);
            fw.write(content);
            fw.close();
            return true;
        } catch (Exception e) {
            logger.error("更新文件失败："+e.getMessage());
            return false;
       }
    }
    /**
     * 读取文件
     * @param fileName 文件路径
     * @return 文件内容
     */
    public String read(String fileName) {
        try {
            java.io.FileReader fr = new java.io.FileReader(PropertiesRead.read("saveArticlePath")+fileName);
            logger.info("读取文件路径："+PropertiesRead.read("saveArticlePath")+fileName);
            char[] buf = new char[1024];
            int len = 0;
            StringBuilder sb = new StringBuilder();
            while ((len = fr.read(buf)) != -1) {
                sb.append(new String(buf, 0, len));
            }
            fr.close();
            return sb.toString();
        } catch (Exception e) {
            logger.error("读取文件失败："+e.getMessage());
            return null;
        }
    }
}
